<template>
  <!-- class="app-container" -->
  <div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['mes:pro:workorder:export']" size="mini" @click="handleExport">导出</el-button>
      </el-col>
      <!-- <right-toolbar @queryTable="getList"></right-toolbar> -->
    </el-row>

    <el-table v-loading="loading" border :data="workorderbomList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="BOM物料编号" width="120" prop="itemCode" :show-overflow-tooltip="true" />
      <el-table-column label="BOM物料名称" width="200" prop="itemName" :show-overflow-tooltip="true" />
      <el-table-column label="规格型号" prop="itemSpc" :show-overflow-tooltip="true" />
      <el-table-column label="单位" :formatter="unitOfMeasure" prop="unitOfMeasure" :show-overflow-tooltip="true" />
      <el-table-column label="物料/产品" prop="itemOrProduct" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_item_product" :value="scope.row.itemOrProduct" />
        </template>
      </el-table-column>
      <el-table-column label="预计使用量" prop="quantity" :show-overflow-tooltip="true" />
      <el-table-column label="操作" width="190px" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status == 'PREPARE'" v-hasPermi="['mes:pro:workorder:edit']" size="mini" type="text"
            @click="handleUpdate(scope.row)">修改</el-button>
          <el-button
            v-if="workorder.status == 'CONFIRMED' && scope.row.itemOrProduct == 'PRODUCT' && workorder.workorderType == 'SELF'"
            v-hasPermi="['mes:pro:workorder:edit']" size="mini" type="text"
            @click="handleAddSubWorkorder(scope.row)">生成工单</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page-sizes="[20, 50, 100]" :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改生产工单BOM组成对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="预计使用量" prop="quantity">
          <el-input v-model="form.quantity" style="width: 100%;" placeholder="请输入预计使用量" />
          <!-- <el-input v-model="form.quantity" placeholder="请输入预计使用量" /> -->
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Workorderbom">
import { listWorkorderbom, getWorkorderbom, delWorkorderbom, addWorkorderbom, updateWorkorderbom } from '@/api/mes/pro/workorderbom'
import { listAllUnitmeasure } from '@/api/mes/pro/workorder'


const proxy = getCurrentInstance()
const mes_item_product = proxy.useDict('mes_item_product')

const props = defineProps({
  optType: {
    type: [String, Number, Boolean, Object, Array, null, undefined],
    default: undefined
  },
  workorder: {
    type: [String, Number, Boolean, Object, Array, null, undefined],
    default: undefined
  }
})
// 遮罩层
const loading = ref(true)
// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
// 生产工单BOM组成表格数据
const workorderbomList = ref([])
// 弹出层标题
const title = ref('')

// 是否显示弹出层
const open = ref(false)
// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 20,
  workorderId: null,
  itemId: null,
  itemCode: null,
  itemName: null,
  itemSpc: null,
  unitOfMeasure: null,
  itemOrProduct: null,
  quantity: null
})
// 单位列表
const measureOptions = ref([])

// 表单参数
const form = ref({})

const rules = ref({
  workorderId: [
    { required: true, message: '生产工单ID不能为空', trigger: 'blur' }
  ],
  itemId: [
    { required: true, message: 'BOM物料ID不能为空', trigger: 'blur' }
  ],
  itemCode: [
    { required: true, message: 'BOM物料编号不能为空', trigger: 'blur' }
  ],
  itemName: [
    { required: true, message: 'BOM物料名称不能为空', trigger: 'blur' }
  ],
  unitOfMeasure: [
    { required: true, message: '单位不能为空', trigger: 'blur' }
  ],
  itemOrProduct: [
    { required: true, message: '物料产品标识不能为空', trigger: 'blur' }
  ],
  quantity: [
    { required: true, message: '预计使用量不能为空', trigger: 'blur' },
    { pattern: /^[1-9]\d{0,7}$/, message: '请输入8位数以内的正整数', trigger: ['blur', 'change'] }
  ]
})
/** 查询生产工单BOM组成列表 */
function getList() {
  loading.value = true
  queryParams.workorderId = props.workorder.workorderId
  listWorkorderbom(queryParams).then(response => {
    workorderbomList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}


// 取消按钮
function cancel() {
  open.value = false
  reset()
}

function getUnits() {
  listAllUnitmeasure().then(response => {
    measureOptions.value = response.data
  })
}


// 表单重置
function reset() {
  let forms = {
    lineId: null,
    workorderId: null,
    itemId: null,
    itemCode: null,
    itemName: null,
    itemSpc: null,
    unitOfMeasure: null,
    itemOrProduct: null,
    quantity: null,
    remark: null,
    attr1: null,
    attr2: null,
    attr3: null,
    attr4: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  // 逐个属性重置（保留对象引用）
  Object.keys(forms).forEach(key => {
    form.value[key] = resetValues[key]
  })
  proxy.resetForm('form')
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}


/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryForm')
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.lineId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}


/** 修改按钮操作 */
function handleUpdate(row) {
  this.reset()
  const lineId = row.lineId || ids.value
  getWorkorderbom(lineId).then(response => {
    form.value = response.data
    open.value = true
    title.value = '修改生产工单BOM组成'
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs['form'].validate(valid => {
    if (valid) {
      if (form.value.lineId != null) {
        updateWorkorderbom(form.value).then(response => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addWorkorderbom(form.value).then(response => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

const emit = defineEmits(['handleAddSub']);

function handleAddSubWorkorder(row) {
  var temp = JSON.parse(JSON.stringify(props.workorder))
  temp.workorderCode = null
  temp.workorderName = row.itemName + '【' + row.quantity + '】' + row.unitOfMeasure
  temp.productId = row.itemId
  temp.productCode = row.itemCode
  temp.productName = row.itemName
  temp.unitOfMeasure = row.measureId
  temp.quantity = row.quantity
  temp.status = 'PREPARE'
  emit('handleAddSub', temp)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('mes/pro/workorderbom/export', {
    ...queryParams
  }, `workorderbom_${new Date().getTime()}.xlsx`)
}

/**
 * 单位翻译
 */
function unitOfMeasure(row) {
  return proxy.selectunitOfMeasure(measureOptions.value, row.unitOfMeasure)
}

getUnits()
getList()

</script>
